/*
 *  @(#)HttpUtil.java  1.0   2012-12-24
 *  Copyright (c) 2012, 北京优听信息技术有限公司
 */
package com.wdt.data.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wdt.data.controller.ReceiveDataApi;
import com.wdt.data.model.BasHeatcompany;
import com.wdt.data.service.IBasHeatcompanyService;
import com.wdt.data.util.redis.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类或接口：HttpUtil<br>
 * 功能描述：Http相关工具类
 *
 * @author Xu Tieqiang
 * @version 1.0
 * @librarys
 */
public class HttpUtil {
    /**
     * 成员方法：request()<br>
     * 功能描述：请求Http URL
     *
     * @param url        - String类型，请求的URL
     * @param parameters - String类型，请求的参数
     * @param method     - String类型，请求的方法{"get"|"post"},默认为get
     * @param charset    - String类型，请求的方法{"get"|"post"},默认为utf-8
     * @return String - String类型,response结果（不包含response头）
     * @throws
     */
    public static String request(String url, String parameters, String method, String charset) {
        if (url == null || url.trim().length() <= 0)
            return "";
        if (method == null || method.trim().length() <= 0)
            method = "get";
        if (charset == null || charset.trim().length() <= 0)
            charset = "utf-8";
        StringBuffer lines = new StringBuffer();
        URLConnection urlConnection = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            if (parameters.trim().length() > 0) {
                String[] para = parameters.split("&");
                Map<String, String> map = strings2map(para);
                Object[] arr = map.keySet().toArray();
                for (int i = 0; i < arr.length; i++) {
                    map.put(arr[i].toString(), URLEncoder.encode(map.get(arr[i].toString()), "utf-8"));
                }
                parameters = mapToString(map);
            }
            urlConnection = new URL(url + ((parameters.trim().length() <= 0) ? "" : "?") + parameters.trim()).openConnection();// 打开一个连接
            urlConnection.setConnectTimeout(10000); // 连接超时10秒
            urlConnection.setReadTimeout(10000); // 读取超时10秒
            urlConnection.setUseCaches(false); // 不使用缓存
            inputStream = urlConnection.getInputStream();// 打开的连接读取的输入流。
            inputStreamReader = new InputStreamReader(inputStream, charset);
            bufferedReader = new BufferedReader(inputStreamReader);
            String line = bufferedReader.readLine();
            while (line != null) {
                lines.append(line + "\n");
                line = bufferedReader.readLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null)
                    bufferedReader.close();
            } catch (Exception e) {
            }
            try {
                if (inputStreamReader != null)
                    inputStreamReader.close();
            } catch (Exception e) {
            }
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (Exception e) {
            }

        }
        return lines.toString();
    }

    public static String requestEncoded(String url, String encodedParameters, String method, String charset) {
        if (url == null || url.trim().length() <= 0)
            return "";
        if (method == null || method.trim().length() <= 0)
            method = "get";
        if (charset == null || charset.trim().length() <= 0)
            charset = "utf-8";
        StringBuffer lines = new StringBuffer();
        URLConnection urlConnection = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            urlConnection = new URL(url + ((encodedParameters.trim().length() <= 0) ? "" : "?") + encodedParameters.trim()).openConnection();// 打开一个连接
            urlConnection.setConnectTimeout(10000); // 连接超时10秒
            urlConnection.setReadTimeout(10000); // 读取超时10秒
            urlConnection.setUseCaches(false); // 不使用缓存
            inputStream = urlConnection.getInputStream();// 打开的连接读取的输入流。
            inputStreamReader = new InputStreamReader(inputStream, charset);
            bufferedReader = new BufferedReader(inputStreamReader);
            String line = bufferedReader.readLine();
            while (line != null) {
                lines.append(line + "\n");
                line = bufferedReader.readLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null)
                    bufferedReader.close();
            } catch (Exception e) {
            }
            try {
                if (inputStreamReader != null)
                    inputStreamReader.close();
            } catch (Exception e) {
            }
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (Exception e) {
            }

        }
        return lines.toString();
    }

    public static Map requestHeader(String url, String parameters, String method, String charset) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map headerMap = new HashMap();
        resultMap.put("result", "");
        resultMap.put("header", "");
        if (url == null || url.trim().length() <= 0) return resultMap;
        if (method == null || method.trim().length() <= 0) method = "GET";
        if (charset == null || charset.trim().length() <= 0) charset = "utf-8";
        StringBuffer lines = new StringBuffer();
        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
//			if(parameters.trim().length()>0){
//				String[] para = parameters.split("&") ;
//				Map<String,String> map = strings2map(para) ;
//				Object[] arr = map.keySet().toArray() ;
//				for(int i=0 ;i<arr.length;i++){
//					map.put(arr[i].toString(), URLEncoder.encode(map.get(arr[i].toString()), "utf-8")) ;
//				}
//				parameters = mapToString(map) ;
//			}
            if (method.equalsIgnoreCase("post")) {
                urlConnection = (HttpURLConnection) new URL(url).openConnection();//打开一个连接
                urlConnection.setRequestMethod(method.toUpperCase());
                urlConnection.setDoOutput(true);
                urlConnection.getOutputStream().write(parameters.trim().getBytes());
            } else {
                urlConnection = (HttpURLConnection) new URL(url + ((parameters.trim().length() <= 0) ? "" : "?") + parameters.trim()).openConnection();//打开一个连接
                urlConnection.setUseCaches(false); //不使用缓存
            }
            urlConnection.setConnectTimeout(10000); //连接超时10秒
            urlConnection.setReadTimeout(10000); //读取超时10秒
            inputStream = urlConnection.getInputStream();//打开的连接读取的输入流。
            inputStreamReader = new InputStreamReader(inputStream, charset);
            bufferedReader = new BufferedReader(inputStreamReader);
            headerMap = urlConnection.getHeaderFields();
            String line = bufferedReader.readLine();
            while (line != null) {
                lines.append(line + "\n");
                line = bufferedReader.readLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) bufferedReader.close();
            } catch (Exception e) {
            }
            try {
                if (inputStreamReader != null) inputStreamReader.close();
            } catch (Exception e) {
            }
            try {
                if (inputStream != null) inputStream.close();
            } catch (Exception e) {
            }

        }
        resultMap.put("result", lines.toString());
        resultMap.put("header", headerMap);
        return resultMap;
    }

    public static Map getHeader(String url, String parameters) {
        Map<String, List<String>> headerMap = new HashMap<String, List<String>>();
        if (url == null || url.trim().length() <= 0)
            return headerMap;
        URLConnection urlConnection = null;
        try {
            if (parameters.trim().length() > 0) {
                String[] para = parameters.split("&");
                Map<String, String> map = strings2map(para);
                Object[] arr = map.keySet().toArray();
                for (int i = 0; i < arr.length; i++) {
                    map.put(arr[i].toString(), URLEncoder.encode(map.get(arr[i].toString()), "utf-8"));
                }
                parameters = mapToString(map);
            }
            urlConnection = new URL(url + ((parameters.trim().length() <= 0) ? "" : "?") + parameters.trim()).openConnection();// 打开一个连接
            urlConnection.setConnectTimeout(10000); // 连接超时10秒
            urlConnection.setReadTimeout(10000); // 读取超时10秒
            urlConnection.setUseCaches(false); // 不使用缓存
            headerMap = urlConnection.getHeaderFields();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return headerMap;
    }

    private static Map<String, String> strings2map(String[] strData) {
        Map<String, String> result = new HashMap<String, String>();
        for (int i = 0; i < strData.length; i++) {
            // 查找下一个里是否有=号，如果没有就把下一个并入本串
            if (i < strData.length - 1 && strData[i + 1].indexOf("=") == -1) {
                strData[i] += "&" + strData[i + 1];
            }
            int token = strData[i].indexOf("=");
            if (token == -1)
                continue; // 如果本串中没有=号，则跳到下一个串解析（已并入上一个串中）
            // 将等号前面的为Key,等号后面的为Value
            try {
                result.put(strData[i].substring(0, token), strData[i].substring(token + 1));
            } catch (Exception e) {
                // 产生异常outofindex一般是由于tm参数值里有&特殊字符，导致该数组中某值没有=符号
                System.out.println("执行Pv2Adapter类的strings2map()方法时发生错误，参数String[]为：");
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String mapToString(Map map) {
        StringBuffer sb = new StringBuffer();
        Object[] arr = map.keySet().toArray();
        for (int i = 0; i < arr.length; i++) {
            sb.append(arr[i].toString() + "=" + map.get(arr[i].toString()) + "&");
        }
        if (sb.charAt(sb.length() - 1) == '&') {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    /**
     * 判断URL是否存在 ，（连续访问20次，并延迟1秒钟：主要是用在国际台和中华radio的图片上传）
     *
     * @param url1
     * @return
     */
    public static boolean judgeUrl(String url1) {
        boolean b = false;
        int count = 1;
        URL url = null;
        HttpURLConnection con = null;
        while (count < 20) {
            try {
                url = new URL(url1);
                con = (HttpURLConnection) url.openConnection();
                int state = 0;
                state = con.getResponseCode();
                if (state == 200) {
                    b = true;
                    break;
                } else {
                    count++;
                    Thread.sleep(1000);
                }
            } catch (IOException e) {
                count++;
                e.printStackTrace();
            } catch (InterruptedException e) {
                count++;
                e.printStackTrace();
            }
        }
        return b;
    }

    /**
     * 成员方法：requestPost()<br>
     * 功能描述：请求Http URL
     *
     * @param url        - String类型，请求的URL
     * @param parameters - String类型，请求的参数
     * @param -          String类型，请求的方法{"get"|"post"},默认为post
     * @return String - String类型,response结果（不包含response头）
     * @throws
     */

    public static String requestPost(String url, String parameters) {
        if (url == null || url.trim().length() <= 0) return "";

        StringBuffer sb = new StringBuffer();  // 接收并返回的变量
        OutputStreamWriter out = null;  // 输出流 发送
        BufferedReader in = null;  // 输入流 接收

        try {
            URL realUrl = new URL(url);  //　获取url 对象
            //打开url 连接
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // post 请求设置的参数
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            // 定义输出流 准备发送数据用
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            //发送数据到指定的 url
            out.write(parameters);
            // 刷新缓存
            out.flush();
            // 接收指定url返回的数据的流
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = "";
            // 从指定url中读取 数据到本地变量中sb
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }

            System.out.println("发送POST请求成功......");
        } catch (Exception e) {
            System.out.println("发送POST请求失败......" + e);
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return sb.toString();
    }

    /**
     * 沧州接收上报数据
     * @param request
     * @return
     */
    public static R getParm(HttpServletRequest request, String json) {
        Logger logger = LoggerFactory.getLogger(HttpUtil.class);

        System.out.println("接受数据>>>>>>>>>>>>>>>>>>>"+json);
        IBasHeatcompanyService iBasHeatcompanyService = SpringContextUtils.getBean(IBasHeatcompanyService.class);
        RedisUtils redisUtils = SpringContextUtils.getBean(RedisUtils.class);
        if (StringUtils.isEmpty(json)){
            return R.error("json字符串为空");
        }
        try {
            Map map = JsonUtil.fromJson(json,Map.class);
            logger.info("接受{}的数据>>>>>>>>>>>>>>>>>>>"+json,map.get("heatCompanyId"));
            if (StringUtils.isEmpty(map.get("requestId"))){
                return R.ok("","4","requestId为空");
            }
            String requestId = map.get("requestId").toString();
            if (StringUtils.isEmpty(map.get("token"))){
                return R.ok(requestId,"4","token为空");
            }
            if (StringUtils.isEmpty( map.get("heatCompanyId"))){
                return R.ok(requestId,"","4","heatCompanyId为空");
            }
            String heatCompanyId = map.get("heatCompanyId").toString();
            if (StringUtils.isEmpty(redisUtils.get(map.get("token").toString()))){
                return R.ok(requestId,"4","token不正确或已失效");
            }
            if (!redisUtils.get(map.get("token").toString()).equals(heatCompanyId)){
                return R.ok(requestId,heatCompanyId,"4","token与公司不匹配，请检查后重试");
            }
            QueryWrapper<BasHeatcompany> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("code",heatCompanyId);
            BasHeatcompany basHeatcompany = iBasHeatcompanyService.getOne(queryWrapper);
            if (basHeatcompany == null){
                return R.ok(requestId,heatCompanyId,"4","供热企业代码不正确");
            }
            String requestTime = request.getParameter("requestTime");
            if (StringUtils.isEmpty(map.get("dataList"))){
                return R.ok(requestId,heatCompanyId,"4","dataList数据不存在");
            }
            List<Map> list = JsonUtil.fromJson(map.get("dataList").toString(), ArrayList.class);
            return R.ok(requestId,heatCompanyId,"0","",list);
        }catch (Exception e){
            return R.error("json格式有误");
        }

    }

}
